import re
from time import timezone

from django.core.validators import RegexValidator
from django.db import models

# Create your models here.
from django.db import models
from django.db.models import Max




class Resource(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=100)
    url = models.CharField(max_length=255, blank=True, null=True)
    pid = models.ForeignKey('self', on_delete=models.CASCADE, related_name='children', null=True, blank=True)
    def __str__(self):
        return self.name
    class Meta:
        verbose_name_plural = '资源表'
        db_table = 'keep_resource'
class Role(models.Model):
    ROLE_CHOICES = {
        (0, '基础角色'),
        (1, '正常角色'),
    }
    type = models.SmallIntegerField(choices=ROLE_CHOICES, default=1, verbose_name='角色身份')
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=100, unique=True)
    resource = models.ManyToManyField(Resource, related_name='roles')
    pid = models.ForeignKey('self', on_delete=models.CASCADE, related_name='inherit_role', null=True, blank=True)
    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = '角色表'
        db_table = 'role'



class StaffModelManager(models.Manager):
    def get_next_staff_id(self):
        # 获取当前日期
        today = timezone.now().date()
        # 格式化日期为 YYYYMMDD
        date_str = today.strftime('%Y%m%d')
        # 查询当前日期下最大的编号
        max_id = self.get_queryset().filter(staff_id__startswith=date_str).aggregate(Max('staff_id'))['staff_id__max']
        if max_id is None:
            # 如果是当天的第一个记录，编号为日期字符串后跟0001
            return f"{date_str}0001"
        else:
            # 否则，找到编号的数字部分并递增
            number_part = int(max_id[len(date_str):])
            return f"{date_str}{number_part + 1:04d}"

class StaffModel(models.Model):
    staff_id = models.IntegerField(unique=True)
    avatar = models.ImageField(upload_to='staff/', blank=True, null=True)
    name = models.CharField(max_length=100,verbose_name="姓名")
    username = models.CharField(max_length=100, unique=True, blank=True, null=True,verbose_name="用户名")
    password = models.CharField(max_length=100, blank=True, null=True,verbose_name="密码")
    phone = models.CharField(max_length=11,blank=True, null=True,verbose_name="手机号")
    update_person = models.CharField(max_length=100, blank=True, null=True,verbose_name="更新人")
    update_time = models.DateField(auto_now=True,verbose_name="更新时间")
    roleid = models.ForeignKey(Role, on_delete=models.SET_NULL, null=True,related_name='users',verbose_name="角色")
    dept_id = models.ForeignKey('Department', on_delete=models.CASCADE,related_name='department', null=True,
                                verbose_name="部门")
    position = models.ForeignKey('Position',on_delete=models.SET_NULL,related_name='position', null=True,
                                 verbose_name="职位")
    # objects = StaffModelManager()
    # def save(self, *args, **kwargs):
    #     if not self.id:  # 如果是新创建的对象
    #         self.staff_id = self.__class__.objects.get_next_staff_id()
    #     super().save(*args, **kwargs)


    def __str__(self):
        return self.name,self.update_time.strftime('%Y-%m-%d')
    class Meta:
        verbose_name_plural = '用户表'
        db_table = 'keep_staff'
# 互斥表
class Resource_exp(models.Model):
    res1 = models.ForeignKey(Resource, on_delete=models.CASCADE, related_name='resource_exp1',verbose_name="资源1")
    res2 = models.ForeignKey(Resource, on_delete=models.CASCADE, related_name='resource_exp2',verbose_name="资源2")
    def __str__(self):
        return self.res1,self.res2
    class Meta:
        verbose_name_plural = '资源互斥表'
        db_table = 'keep_resource_exp'


# 用户表
class PersonModel(models.Model):
    gender_choices = (
        ('male', '男'),
        ('female', '女'),
        ('other', '其他'),
    )
    user_id = models.CharField(max_length=10,default='1234567890')
    nickname = models.CharField(max_length=50, verbose_name="昵称")
    real_name = models.CharField(max_length=100, verbose_name="真实姓名")
    phone = models.CharField(max_length=11, verbose_name="手机号")
    avatar = models.ImageField(upload_to='avatars/', blank=True, null=True, verbose_name="头像")
    gender = models.CharField(max_length=10, choices=gender_choices, verbose_name="性别")
    birth_date = models.DateField(verbose_name="出生日期")
    address = models.CharField(max_length=255, verbose_name="家庭住址")
    height = models.DecimalField(max_digits=5, decimal_places=2, verbose_name="身高")
    weight = models.DecimalField(max_digits=5, decimal_places=2, verbose_name="体重")
    occupation = models.CharField(max_length=100, verbose_name="职业")
    def __str__(self):
        return self.real_name

    class Meta:
        verbose_name_plural = '人员信息'
        db_table = 'keep_person_info'

# 部门表
class Department(models.Model):
    id = models.AutoField(primary_key=True)  # 主键自增，Django默认会为主键字段添加AutoField，所以这一行可以省略
    name = models.CharField(max_length=50, unique=True)  # 部门名，唯一
    def __str__(self):
        return self.name
    class Meta:
        verbose_name_plural = '部门'
        db_table = 'keep_department'

# 职位表
class Position(models.Model):
    id = models.AutoField(primary_key=True)  # 主键自增，可以省略
    name = models.CharField(max_length=50, unique=True)  # 职位名，唯一
    department = models.ForeignKey('Department', on_delete=models.CASCADE, related_name="departname",verbose_name="所属部门")  # 外键，关联部门表
    def __str__(self):
        return self.name
    class Meta:
        verbose_name_plural = '部门'
        db_table = 'keep_position'
# 新建工作流表
class Workflow(models.Model):
    id = models.AutoField(primary_key=True)  # 主键自增，可以省略
    name = models.CharField(max_length=50, unique=True)  # 名称，唯一
    params = models.TextField()  # 参数字段，json序列化存储（注意：Django 3.1及更高版本使用JSONField，否则您可能需要使用TextField并手动处理JSON）
    status = models.IntegerField(choices=((1, '可用'), (2, '停用')), default=2)  # 状态，1可用 2停用
    def __str__(self):
        return self.name
    class Meta:
        verbose_name_plural = '工作流'
        db_table = 'keep_workflow'


# 任务表
class Task(models.Model):
    id = models.AutoField(primary_key=True, verbose_name="任务id")
    name = models.CharField(max_length=50, verbose_name="任务名称")
    params = models.TextField(verbose_name="任务参数")
    workflow_id = models.ForeignKey('Workflow', on_delete=models.SET_NULL, null = True,related_name='workflow_tasks',verbose_name="工作流表id")
    staffid = models.ForeignKey('StaffModel', on_delete=models.CASCADE, related_name='staff_tasks', verbose_name="员工id")
    next_audit = models.ForeignKey('StaffModel', on_delete=models.CASCADE, related_name='next_audit',verbose_name="下一审批人")
    task_status = models.IntegerField(choices=((0, '未审批'), (1, '已审批'), (2, '已退回，请重新申请')), default=0,verbose_name="任务状态")
    level = models.IntegerField(verbose_name="审批等级", null=True, blank=True)
    class Meta:
        db_table = "keep_workTask"
        verbose_name = "任务表"
        verbose_name_plural = verbose_name


# 审批节点表
class WorkflowApprovalNode(models.Model):
    id = models.AutoField(primary_key=True, verbose_name="审批节点id")
    workflow_id = models.ForeignKey('Workflow', on_delete=models.CASCADE, related_name='approval_workflow',verbose_name="工作流表id")
    position_id = models.ForeignKey('Position', on_delete=models.CASCADE, related_name='approval_position',verbose_name="职位id")
    level = models.IntegerField(verbose_name="审批等级")
    class Meta:
        db_table = "keep_workflow_approval_node"
        verbose_name = "审批节点表"
        verbose_name_plural = verbose_name


# 权限表
class WorkflowPermission(models.Model):
    id = models.AutoField(primary_key=True, verbose_name="权限id")
    role_id = models.ForeignKey('Role', on_delete=models.CASCADE, related_name='permission_role', verbose_name="角色id")
    workflow_id = models.ForeignKey('Workflow', on_delete=models.CASCADE, related_name='permission_workflow',verbose_name="工作流表id")
    class Meta:
        db_table = "keep_workflow_permission"
        verbose_name = "权限表"
        verbose_name_plural = verbose_name
# 审批记录表
class Approval_Record(models.Model):
    task_id = models.ForeignKey(Task,models.CASCADE,related_name='task',blank=True, null=True,verbose_name="任务id")
    audit_user = models.ForeignKey('StaffModel',models.CASCADE,related_name='audit_user',blank=True, null=True,verbose_name="审批人id")
    audit_time = models.DateField(auto_now=True,blank=True, null=True,verbose_name="审批时间")
    audit_status = models.CharField(max_length=10,choices=[
            ('pending', '待审批'),
            ('approved', '已审批'),
            ('rejected', '已拒绝'),
        ],blank=True, null=True,verbose_name="审批状态")
    def __str__(self):
        return self.audit_user

    class Meta:
        db_table = "keep_approval_record"
        verbose_name_plural = "审批记录表"
